<?php
namespace app\api\model\food;

use app\common\model\SignLog as SignLogModel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 签到记录模型
 */
class SignLog extends SignLogModel
{
    /**
     * 添加
     */
    public function add(array $data)
    {
        $new_data[0] = $data;
        $new_data[0]['applet_id'] = self::$applet_id;
        $sign = Setting::getItem('sign');//获取签到配置
        $user = User::get($data['user_id']);//获取用户信息
        //判断奖励数值
        if($sign['mode'] == 'fixed'){
            $new_data[0]['number'] = $sign['number'];//固定值
        }else{
            $new_data[0]['number'] = rand(1,$sign['number']);//随机值
        }
        //判断奖励类型
        if($sign['type'] == 'score'){
            $user->score = ['inc', $new_data[0]['number']];
            $new_data[0]['type'] = 'score';
        }else{
            $user->money = ['inc', $new_data[0]['number']];
            $new_data[0]['type'] = 'money';
        }
        $new_data[0]['remark'] = '每日签到';
        //如果有签到任务
        if(isset($sign['plan']) and sizeof($sign['plan']) > 0){
            $plan = array_sort($sign['plan'], 'days');//按照天数从小到大排序
            $days = Cache::get('food_sign_' . $user['user_id'] . '_' . self::$applet_id,0);
            $days = $days + 1;
            foreach ($plan as $item){
                if($item['days'] == $days){
                    $new_data[1] = $data;
                    $new_data[1]['applet_id'] = self::$applet_id;
                    //判断奖励类型
                    if($item['type'] == 'score'){
                        $user->score = ['inc', $item['number']];
                        $new_data[1]['type'] = 'score';
                    }else{
                        $user->money = ['inc', $item['number']];
                        $new_data[1]['type'] = 'money';
                    }
                    $new_data[1]['number'] = $item['number'];
                    $new_data[1]['remark'] = '任务奖励';
                    break;
                }
            }
            Cache::set('food_sign_' . $user['user_id'] . '_' . self::$applet_id,$days);
        }
        // 开启事务
        Db::startTrans();
        try {
            // 添加记录
            $this->saveAll($new_data);
            $user->save();//更新用户信息
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;  
    }
}
